package com.mantbox.channelcall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mantbox.channelcall.dao.CallInfoMapper;
import com.mantbox.channelcall.entity.CallInfo;
import com.mantbox.channelcall.service.CallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CallServiceImpl implements CallService {

    @Autowired
    CallInfoMapper callInfoMapper;

    @Override
    public void saveCall(String idfa,String callId,String rqId,Integer urlId, String ts,String remark,Integer dataId) {
        CallInfo callInfo = new CallInfo();
        callInfo.setIdfa(idfa);
        callInfo.setCallId(callId);
        callInfo.setRqId(rqId);
        callInfo.setUrlId(urlId);
        callInfo.setCallTime(new Date());
        callInfo.setTs(ts);
        callInfo.setRemark(remark);
        callInfo.setDataId(dataId);
        if (StringUtils.hasLength(rqId)) {
            List<CallInfo> callInfos =  callInfoMapper.seleCallInfoByRqId(rqId);
            if (callInfos.size() > 0) {
                return;
            }
        }
        callInfoMapper.insertSelective(callInfo);
    }

    @Override
    public PageInfo<Map<String,Object>> pageList(Integer page, Integer pageSize, String start, String end) {
        PageHelper.startPage(page,pageSize);
        if (StringUtils.hasLength(end)) {
            DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = dateFormatter.parse(end);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DATE,1);
                date = cal.getTime();
                end = dateFormatter.format(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        List<Map<String,Object>> mapList = callInfoMapper.pageList(start,end);
        return new PageInfo<>(mapList);
    }
}
